//
//  YXFileManager.m
//  MockProject
//
//  Created by FanYu on 29/8/2016.
//  Copyright © 2016 niuzhaowang. All rights reserved.
//

#import "YXTaskManager.h"
#import "YXDownloaderManager.h"
#import "YXBaseDownloadTool.h"

@implementation YXTaskManager

+ (void)loadTaskToDB {
    NSString *filepath = [[NSBundle mainBundle] pathForResource:@"urls" ofType:@"txt"];
    NSError *error;
    NSString *fileContents = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"Error reading file: %@", error.localizedDescription);
    }
    
    NSMutableArray *lineArray = (NSMutableArray *)[fileContents componentsSeparatedByString:@"\n"];
    [lineArray removeObjectAtIndex:0];
    
    for (NSString *line in lineArray) {
        NSArray *fileComponents = [line componentsSeparatedByString:@" ** "];
        YXTaskModel *model = [YXTaskModel configLoadDataWithUID:fileComponents[0] title:fileComponents[1] url:fileComponents[2]];
        [YXTaskManager saveTask:model];
    }
}


+ (void)saveTask:(YXTaskModel *)model {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    DownloadTask *task = [NSEntityDescription insertNewObjectForEntityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    task.title = model.title;
    task.uid = model.uid;
    task.url = model.url;
    task.time = [YXTool currentDate];
    task.status = [NSNumber numberWithInteger:YXTaskStatusNA];
    task.isHidden = [NSNumber numberWithBool:YES];
    task.isSelected = [NSNumber numberWithBool:NO];
    
    // 获取task的大小
    [YXDownloaderManager getTaskSizeByURL:model.url success:^(id size) {
        task.size = size;
    } failure:^(id failure) {
        task.size = failure;
    }];
    
    NSError *error;
    [managedContext save:&error];
    if (error) {
        NSLog(@"YXFileManager - Error: %@", error);
    }
}


+ (DownloadTask *)getTaskAtIndex:(NSInteger)index {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    return taskArray[index];
}


+ (DownloadTask *)getTaskWithUID:(NSInteger)uid {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", [NSString stringWithFormat:@"%ld", uid]];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    return taskArray[0];
}


+ (TaskStatus)getTaskStatusWithUID:(NSInteger)uid {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", [NSString stringWithFormat:@"%ld", uid]];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    if (taskArray.count > 0 ){
        DownloadTask *task = taskArray[0];
    
        if ([task.status isEqualToNumber:[NSNumber numberWithInteger:YXTaskStatusDownloading]]) {
            return YXTaskStatusDownloading;
        } else if ([task.status isEqualToNumber:[NSNumber numberWithInteger:YXTaskStatusPause]]) {
            return YXTaskStatusPause;
        } else if ([task.status isEqualToNumber:[NSNumber numberWithInteger:YXTaskStatusWaiting]]) {
            return YXTaskStatusWaiting;
        } else if ([task.status isEqualToNumber:[NSNumber numberWithInteger:YXTaskStatusFailed]]) {
            return YXTaskStatusFailed;
        } else if ([task.status isEqualToNumber:[NSNumber numberWithInteger:YXTaskStatusPrepare]]) {
            return YXTaskStatusPrepare;
        }
    }
    return YXTaskStatusNA;
}

+ (NSArray *)getTasksByTitleAscendingWithStatus:(TaskStatus)status {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    // 条件查找
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status == %@", [NSNumber numberWithInteger:status]];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    // 首字母排序
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    NSArray *newArray = [collation sortedArrayFromArray:taskArray collationStringSelector:@selector(title)];
        
    return newArray;
}


+ (NSArray *)getTasksWithStatus:(TaskStatus)status byTimeline:(BOOL)newOnTop {
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:!newOnTop];
    request.sortDescriptors = @[sortDesc];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status == %@", [NSNumber numberWithInteger:status]];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    return taskArray;
}


+ (NSArray *)getTasksForInProcess:(BOOL)newOnTop {
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:!newOnTop];
    request.sortDescriptors = @[sortDesc];
    
    NSArray *desiredStatus = @[[NSNumber numberWithInteger:YXTaskStatusPause], [NSNumber numberWithInteger:YXTaskStatusFailed], [NSNumber numberWithInteger:YXTaskStatusPrepare], [NSNumber numberWithInteger:YXTaskStatusWaiting], [NSNumber numberWithInteger:YXTaskStatusDownloading]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.status IN %@", desiredStatus];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    return taskArray;
}


+ (NSArray *)getTasksForInProcessWithoutDownloading:(BOOL)newOnTop {
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:!newOnTop];
    request.sortDescriptors = @[sortDesc];
    
    NSArray *desiredStatus = @[[NSNumber numberWithInteger:YXTaskStatusPause], [NSNumber numberWithInteger:YXTaskStatusFailed], [NSNumber numberWithInteger:YXTaskStatusPrepare], [NSNumber numberWithInteger:YXTaskStatusWaiting]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.status IN %@", desiredStatus];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    return taskArray;
}


+ (NSArray *)getTasksForInProcessWithoutFailed:(BOOL)newOnTop {
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"time" ascending:!newOnTop];
    request.sortDescriptors = @[sortDesc];
    
    NSArray *desiredStatus = @[[NSNumber numberWithInteger:YXTaskStatusPause], [NSNumber numberWithInteger:YXTaskStatusPrepare], [NSNumber numberWithInteger:YXTaskStatusWaiting], [NSNumber numberWithInteger:YXTaskStatusDownloading]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.status IN %@", desiredStatus];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    return taskArray;
}


+ (NSString *)getTasksSizePercentWithUID:(NSString *)uid {
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
   
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", uid];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    if (taskArray.count > 0 ){
        DownloadTask *task = taskArray[0];
        return task.sizePercent;
    }
    return @"NA";
}


+ (NSString *)getTaskFilePathWithUID:(NSString *)uid {
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", uid];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    if (taskArray.count > 0 ){
        DownloadTask *task = taskArray[0];
        return task.filePath;
    }
    return @"NA";
}



+ (NSString *)getTaskProgressPercentWithUID:(NSString *)uid {
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", uid];
    request.predicate = predicate;
    
    NSError *error;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&error];
    
    if (taskArray.count > 0 ){
        DownloadTask *task = taskArray[0];
        return task.progress;
    }
    return @"0.0";
}


+ (void)updateTaskSizePercent:(NSString *)sizePercent withUID:(NSString *)uid {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", [NSString stringWithFormat:@"%@", uid]];
    request.predicate = predicate;
    
    NSError *fetchError;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&fetchError];
    if (fetchError) {
        NSLog(@"TaskList-buttonTapped FetchError: %@", fetchError);
    }
    
    // update param
    if (taskArray.count > 0 && sizePercent != nil) {
        DownloadTask *task = taskArray[0];
        
        task.sizePercent = sizePercent;
        
        // save
        NSError *saveError;
        [task.managedObjectContext save:&saveError];
        if (saveError) {
            NSLog(@"TaskList-buttonTapped SaveError: %@", saveError);
        }
    }
}


+ (void)updateTaskProgressPercent:(CGFloat)progress withUID:(NSString *)uid {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", [NSString stringWithFormat:@"%@", uid]];
    request.predicate = predicate;
    
    NSError *fetchError;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&fetchError];
    if (fetchError) {
        NSLog(@"TaskList-buttonTapped FetchError: %@", fetchError);
    }
    
    // update param
    if (taskArray.count > 0) {
        DownloadTask *task = taskArray[0];
        task.progress = [NSString stringWithFormat:@"%f", progress];
        
        // save
        NSError *saveError;
        [task.managedObjectContext save:&saveError];
        if (saveError) {
            NSLog(@"TaskList-buttonTapped SaveError: %@", saveError);
        }
    }
}

+ (void)updateTaskFilePath:(NSString *)filePath withUID:(NSString *)uid {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", [NSString stringWithFormat:@"%@", uid]];
    request.predicate = predicate;
    
    NSError *fetchError;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&fetchError];
    if (fetchError) {
        NSLog(@"TaskList-buttonTapped FetchError: %@", fetchError);
    }
    
    // update param
    if (taskArray.count > 0) {
        DownloadTask *task = taskArray[0];
        task.filePath = filePath;
        
        // save
        NSError *saveError;
        [task.managedObjectContext save:&saveError];
        if (saveError) {
            NSLog(@"TaskList-buttonTapped SaveError: %@", saveError);
        }
    }
}


+ (void)updateTaskSizeWithUID:(NSString *)uid {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", [NSString stringWithFormat:@"%@", uid]];
    request.predicate = predicate;

    NSError *fetchError;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&fetchError];
    if (fetchError) {
        NSLog(@"TaskList-buttonTapped FetchError: %@", fetchError);
    }
    
    // update param
    if (taskArray.count > 0) {
        DownloadTask *task = taskArray[0];
        
        [YXDownloaderManager getTaskSizeByURL:task.url success:^(id size) {
            task.size = size;
        } failure:^(id failed) {
            task.size = failed;
        }];
        
        // save
        NSError *saveError;
        [task.managedObjectContext save:&saveError];
        if (saveError) {
            NSLog(@"TaskList-buttonTapped SaveError: %@", saveError);
        }
    }
}


+ (void)updateTaskStatus:(TaskStatus)status withUID:(NSInteger)uid {
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", [NSString stringWithFormat:@"%ld", uid]];
    request.predicate = predicate;

    NSError *fetchError;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&fetchError];
    if (fetchError) {
        NSLog(@"TaskList-buttonTapped FetchError: %@", fetchError);
    }
    
    // update param
    if (taskArray.count > 0) {
        DownloadTask *task = taskArray[0];
        task.status = [NSNumber numberWithInteger:status];
        task.time = [YXTool currentDate];
        
        // save
        NSError *saveError;
        [task.managedObjectContext save:&saveError];
        if (saveError) {
            NSLog(@"TaskList-buttonTapped SaveError: %@", saveError);
        }
    }
}


+ (void)updateTaskDownloadSpeed:(NSString *)speed withUID:(NSInteger)uid {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadTask" inManagedObjectContext:managedContext];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = entity;
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", [NSString stringWithFormat:@"%ld", uid]];
    request.predicate = predicate;

    NSError *fetchError;
    NSArray *taskArray = [managedContext executeFetchRequest:request error:&fetchError];
    if (fetchError) {
        NSLog(@"TaskList-buttonTapped FetchError: %@", fetchError);
    }
    
    // update param
    if (taskArray.count > 0) {
        DownloadTask *task = taskArray[0];
        task.speed = speed;
        
        // save
        NSError *saveError;
        [task.managedObjectContext save:&saveError];
        if (saveError) {
            NSLog(@"TaskList-buttonTapped SaveError: %@", saveError);
        }
    }
}


@end
